/**
 * 资讯Api
 */
const db = require('../../config/db')
const dayjs = require('dayjs')

/**
 * 根据学院和运动查找对应资讯
 * @param {*} req 
 * @param {*} res 
 * @returns 
 */
exports.getNews = async (req, res) => {
    try {
        const {college, sport} = req.body
        console.log("college: ", college)
        console.log("sport: ", sport)
        let params = []
        let match
        if(college != "" && sport != "") {
            match = `csn.college = ? and csn.sport = ?`
            params.push(college)
            params.push(sport)
        } else if(college != "") {
            match = `csn.college = ?`
            params.push(college)
        } else if(sport != "") {
            match = `csn.sport = ?`
            params.push(sport)
        } else {
            match = `1=1`
        }
        const sql = `SELECT ns.news_id, ns.cover_url, ns.main_title, ns.sub_title, ns.time 
                    from college_sport_news csn 
                    inner join news ns 
                    on csn.news_id = ns.news_id 
                    where 1=1
                    and ` + match
        const [rows] = await db.query(sql, params)
        res.status(200).json(
            rows.map(row => {
                    console.log("time: ", row.time)
                    return {
                        newsId: row.news_id,
                        coverUrl: row.cover_url,
                        mainTitle: row.main_title,
                        subTitle: row.sub_title,
                        time: dayjs(row.time).format('YYYY-MM-DD HH:mm:ss'),
                        pubStatus: row.pub_status == 1 ? "已发布" : "未发布"
                    }
                    
                }
            )
        )
    } catch (err) {
        console.log("getNews error", err)
        return res.status(500).json({"error": "获取资讯报错!"})
    }
}

/**
 * 根据id查找对应资讯
 */
exports.getNewsById = async(req, res) => {
    try {
        const {newsId} = req.body
        console.log("newsId: ", newsId)
        const sql = `SELECT news_id, cover_url, main_title, sub_title, content, time from news
                     where news_id = ?`
        const [rows] = await db.query(sql, [newsId])
        if(rows.length == 0) {
            return res.status(201).json({"error": "找不到该资讯，或已被删除!"})
        }
        const row = rows[0]
        console.log("row: ", row)
        res.status(200).json({
            newsId: row.news_id,
            coverUrl: row.cover_url,
            mainTitle: row.main_title,
            subTitle: row.sub_title,
            content: row.content,
            time: row.time
        })
    } catch(err) {
        console.log("getNewById error",err)
        return res.status(500).json({"error": "获取资讯报错!"})
    }
}